import { getConnectionResult, getAdditionalArgs, defaultParams } from "@/util/graphql/connection";
import { getPrivilege } from "@/util/privilege";
import * as Nexus from "@nexus/schema";
import { Prisma } from "@prisma/client";
import { tansformSelect } from "@/util/graphql/transform_select";

const privilegeList = [
  "ADMIN",

  // 超管
  "SUPERADMIN",
];

const additionalArgs = getAdditionalArgs({
  // 特权
  privilege: getPrivilege({
    fieldName: "Store",
    fieldDescription: "店铺",
    privilegeList,
  }),
  // 类型
  id: Nexus.stringArg({
    description: "店铺id",
  }),
  name: Nexus.stringArg({ description: "名称模糊查询" }),
});
// 拓展类型
export default Nexus.extendType({
  // 类型
  type: "Query",

  // 定义
  definition: (t) => {
    // 用户
    t.connection("storeConnection", {
      ...(defaultParams as any),
      additionalArgs,
      type: "Store",

      // 权限认证
      authorize: (_root, _args, ctx, info) => {
        return ctx.service.authenticate.authenticate(info);
      },
      resolve: async (_root, args, ctx, info) => {
        const { db, token } = ctx;
        const {
          sub: { adminId },
        } = token;

        const { privilege, id, name } = args;

        // 查询参数
        const whereInputParams: Prisma.StoreWhereInput = {};

        if (id) {
          whereInputParams.id = id;
        }

        switch (privilege) {
          case "ADMIN": {
            break;
          }
        }

        if (name) {
          whereInputParams.name = { contains: name };
        }

        const select = tansformSelect(info.fieldNodes);

        // 解析查询参数

        const findManyParams: Prisma.StoreFindManyArgs = { select };

        if (whereInputParams) {
          findManyParams.where = whereInputParams;
        }

        // 定义默认排序
        const defaultOrderByInputList: Prisma.StoreOrderByWithRelationInput[] = [
          {
            createdAt: "desc",
          },
        ];

        return await getConnectionResult({
          tableModel: db.store,
          args,
          findManyParams,
          defaultOrderByInputList,
        });
      },
    });
  },
});
